import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  id: number
  username: string
  email: string
  avatar?: string
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const isLoggedIn = ref<boolean>(false)

  // 计算属性
  const userName = computed(() => userInfo.value?.username || '游客')
  const userAvatar = computed(() => userInfo.value?.avatar || '')

  // 方法
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    isLoggedIn.value = true
  }

  const setToken = (newToken: string) => {
    token.value = newToken
  }

  const login = async (username: string, password: string) => {
    try {
      // 这里应该调用登录API
      console.log('登录', { username, password })
      
      // 模拟登录成功
      const mockUser: UserInfo = {
        id: 1,
        username,
        email: `${username}@example.com`
      }
      
      setUserInfo(mockUser)
      setToken('mock-token-123')
      
      return { success: true }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败' }
    }
  }

  const logout = () => {
    userInfo.value = null
    token.value = ''
    isLoggedIn.value = false
  }

  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,
    // 计算属性
    userName,
    userAvatar,
    // 方法
    setUserInfo,
    setToken,
    login,
    logout
  }
})
